package bag

import (
	"context"
	"encoding/json"
	"github.com/gogf/gf/v2/util/gconv"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/event"
	"xr-game-server/core/httpserver"
	"xr-game-server/dao/bagdao"
	"xr-game-server/dto/bagdto"
	"xr-game-server/entity"
	"xr-game-server/errercode"
	"xr-game-server/gamecfg"
	"xr-game-server/gameevent"
	"xr-game-server/module/protocol"
)

func newArrayCellDto(dbs []*entity.PlayerBag) []*protocol.ItemModel {
	ret := make([]*protocol.ItemModel, common.Zero)
	for _, db := range dbs {
		ret = append(ret, newCellDto(db))
	}
	return ret
}
func newCellDto(db *entity.PlayerBag) *protocol.ItemModel {
	ret := &protocol.ItemModel{
		Id:  db.CfgId,
		Val: db.Val,
	}
	return ret
}

func GetBag(ctx context.Context, req *bagdto.GetBagReq) (res *bagdto.GetBagRes, err error) {
	roleId := httpserver.GetAuthId(ctx)
	cacheData := bagdao.GetBagCells(gconv.Uint64(roleId))
	bagData := make([]*entity.PlayerBag, common.Zero)
	for _, db := range cacheData {
		if db.Val > common.Zero {
			bagData = append(bagData, db)
		}
	}
	return bagdto.NewGetBagRes(bagData), nil
}

func UseProp(ctx context.Context, req *bagdto.UsePropReq) (res *bagdto.UsePropRes, err error) {
	roleId := httpserver.GetAuthId(ctx)
	itemCfg := gamecfg.GetItemById(req.Item.Id)
	if itemCfg == nil {
		return nil, errercode.CreateCode(errercode.ItemNon)
	}
	itemHandler := protocol.GetItemHandlerBy(itemCfg.ItemHandler)
	if itemHandler == nil {
		return nil, errercode.CreateCode(errercode.ItemNon)
	}
	if !itemHandler.CanConsume(roleId, req.Item) {
		return nil, errercode.CreateCode(errercode.ItemNumber)
	}
	propHandler := protocol.GetPropHandler(itemCfg.PropHandler)
	if propHandler == nil {
		return nil, errercode.CreateCode(errercode.PropNon)
	}
	req.Item.TypeId = common.Subtract
	//道具使用参数格式:[来源id,经验id,参数]
	var param []uint64
	json.Unmarshal([]byte(itemCfg.PropParam), &param)
	//声明来源
	req.Item.Source = gamecfg.GetItemSourceById(param[0])

	items := make([]*protocol.ItemModel, common.Zero)
	items = append(items, req.Item)
	itemHandler.Consume(roleId, items, true)
	propHandler.Use(roleId, req.Item)
	//发送物品日志
	event.Pub(gameevent.ItemChange, gameevent.NewItemChangeData(roleId, []*protocol.ItemModel{req.Item}))
	return bagdto.NewUsePropRes(), nil
}
